import { NodeProps } from '@/components/workflow/types'
import CallWordDia from '@/pages/ApplicationEditPage/components/CallWordDia'
import OptionDia from '@/pages/ApplicationEditPage/components/OptionDia'
import { CaretRightOutlined } from '@ant-design/icons'
import type { CollapseProps } from 'antd'
import { Collapse, theme } from 'antd'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { showMessage } from '../../../../components/antd-comp/message/index'
// import CallWordCont from './component/CallWordCont'
import { useWorkFlowStore } from '@/store/workflowStore'
// import { useSourceOptions } from '../../hooks/use-source-options'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import RunDrawer from '../components/RunDrawer'
import ExportationCont from './component/ExportationCont'
import InputCont from './component/InputCont'
import InputContNew from './component/InputContOld'
import LimModeCont from './component/LimModeCont'
import UserCallWordCont from './component/UserCallWordCont'
import { getLlmDefaultParams } from './default'
import './index.less'

/* 大模型node */
const LLMNode: FC<NodeProps> = ({ id, data }: any) => {
  const { flowVariables, setFlowVariables } = useWorkFlowStore()
  // const { options: sourceOptions } = useSourceOptions(data)

  const { token } = theme.useToken()
  const panelStyle: React.CSSProperties = {
    marginBottom: 24,
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: 'none'
  }

  const createCollapseItem = (key: string, label: JSX.Element, children: JSX.Element) => ({
    key,
    label,
    children,
    style: panelStyle
  })

  /* 系统提示词 */
  // const CallWordNode = () => (
  //   <div className="flexRowStart flexRowJustBet">
  //     <div className="flexRowStart">
  //       <span className="lim_case_tem_title">系统提示词</span>
  //       <Tooltip placement="top" title={'为对话提供系统级指导，如设定人设和回复逻辑。'} arrow>
  //         <div className="cursonCase lim_iconCase">
  //           <IndivduationDiaIcon />
  //         </div>
  //       </Tooltip>
  //     </div>
  //     <div className="flexRowStart">
  //       {/* 题库 */}
  //       <Tooltip placement="top" title={'提示词库'} arrow>
  //         <div
  //           className="limModeCont_svgBut cursonCase flexRow"
  //           onClick={e => {
  //             e.stopPropagation()
  //             setCallOpen(true)
  //           }}
  //         >
  //           <svg
  //             className="icon-icon icon-icon-coz_knowledge "
  //             width="1em"
  //             height="1em"
  //             viewBox="0 0 24 24"
  //             fill="currentColor"
  //             xmlns="http://www.w3.org/2000/svg"
  //             color="rgba(107, 109, 117, 1)"
  //           >
  //             <path d="M10 9C10 8.44772 10.4477 8 11 8H17C17.5523 8 18 8.44772 18 9 18 9.55228 17.5523 10 17 10H11C10.4477 10 10 9.55228 10 9zM11 13C10.4477 13 10 13.4477 10 14 10 14.5523 10.4477 15 11 15H15C15.5523 15 16 14.5523 16 14 16 13.4477 15.5523 13 15 13H11z"></path>
  //             <path
  //               fill-rule="evenodd"
  //               clip-rule="evenodd"
  //               d="M6 4C6 2.89543 6.89543 2 8 2H18C20.2091 2 22 3.79086 22 6V20C22 21.1046 21.1046 22 20 22H10C7.79086 22 6 20.2091 6 18V4ZM8 4H18C19.1046 4 20 4.89543 20 6V20H10C8.89543 20 8 19.1046 8 18V4Z"
  //             ></path>
  //             <path d="M4 4C2.89543 4 2 4.89543 2 6V18C2 19.1046 2.89543 20 4 20V4Z"></path>
  //           </svg>
  //         </div>
  //       </Tooltip>
  //       {/* 优化 */}
  //       <Tooltip placement="top" title={'自动优化提示词'} arrow>
  //         <div
  //           className="limModeCont_svgBut cursonCase flexRow"
  //           style={{ marginLeft: '10px', color: 'rgba(78,64,229,1)' }}
  //           onClick={e => {
  //             e.stopPropagation()
  //             setCallWordOpen(true)
  //           }}
  //         >
  //           <svg
  //             className="icon-icon icon-icon-coz_ai_fill coz-ai-button-icon coz-fg-hglt"
  //             width="1em"
  //             height="1em"
  //             viewBox="0 0 24 24"
  //             fill="currentColor"
  //             xmlns="http://www.w3.org/2000/svg"
  //           >
  //             <path d="M18.9839 1.85931C19.1612 1.38023 19.8388 1.38023 20.0161 1.85931L20.5021 3.17278C20.5578 3.3234 20.6766 3.44216 20.8272 3.49789L22.1407 3.98392C22.6198 4.1612 22.6198 4.8388 22.1407 5.01608L20.8272 5.50211C20.6766 5.55784 20.5578 5.6766 20.5021 5.82722L20.0161 7.14069C19.8388 7.61977 19.1612 7.61977 18.9839 7.14069L18.4979 5.82722C18.4422 5.6766 18.3234 5.55784 18.1728 5.50211L16.8593 5.01608C16.3802 4.8388 16.3802 4.1612 16.8593 3.98392L18.1728 3.49789C18.3234 3.44216 18.4422 3.3234 18.4979 3.17278L18.9839 1.85931zM13.5482 4.07793C13.0164 2.64069 10.9836 2.64069 10.4518 4.07793L8.99368 8.01834C8.82648 8.47021 8.47021 8.82648 8.01834 8.99368L4.07793 10.4518C2.64069 10.9836 2.64069 13.0164 4.07793 13.5482L8.01834 15.0063C8.47021 15.1735 8.82648 15.5298 8.99368 15.9817L10.4518 19.9221C10.9836 21.3593 13.0164 21.3593 13.5482 19.9221L15.0063 15.9817C15.1735 15.5298 15.5298 15.1735 15.9817 15.0063L19.9221 13.5482C21.3593 13.0164 21.3593 10.9836 19.9221 10.4518L15.9817 8.99368C15.5298 8.82648 15.1735 8.47021 15.0063 8.01834L13.5482 4.07793zM5.01608 16.8593C4.8388 16.3802 4.1612 16.3802 3.98392 16.8593L3.49789 18.1728C3.44216 18.3234 3.3234 18.4422 3.17278 18.4979L1.85931 18.9839C1.38023 19.1612 1.38023 19.8388 1.85931 20.0161L3.17278 20.5021C3.3234 20.5578 3.44216 20.6766 3.49789 20.8272L3.98392 22.1407C4.1612 22.6198 4.8388 22.6198 5.01608 22.1407L5.50211 20.8272C5.55784 20.6766 5.6766 20.5578 5.82722 20.5021L7.14069 20.0161C7.61977 19.8388 7.61977 19.1612 7.14069 18.9839L5.82722 18.4979C5.6766 18.4422 5.55784 18.3234 5.50211 18.1728L5.01608 16.8593z"></path>
  //           </svg>
  //         </div>
  //       </Tooltip>
  //     </div>
  //   </div>
  // )

  const [textValue, setTextValue] = useState('')
  const [callwordOpen, setCallWordOpen] = useState(false)
  const [callOpen, setCallOpen] = useState(false)
  /* 提交 */
  const submitData = data => {
    setTextValue(data)
    setCallWordOpen(false)
  }
  /* 添加 */
  const addCallWord = (e: any) => {
    setTextValue(e.content ? e.content : '')
    showMessage({
      content: '添加成功',
      type: 'success'
    })
    setCallOpen(false)
  }
  const [info, setInfo] = useState({ ...getLlmDefaultParams() }) as any

  const getSourceOptions = info => {
    return info.inputList
      ? info.inputList.filter(input => input.variable).map(input => ({ value: input.variable, label: input.variable }))
      : []
  }

  const [sourceOptions, setSourceOptions] = useState<{ value: string; label: string }[]>(getSourceOptions(info))
  const editData = e => {
    const obj = { ...info, ...e }
    setInfo(obj)
    setFlowVariables(id, data.title, obj)
    setSourceOptions(getSourceOptions(obj))
  }

  // const [sourceOptions, setSourceOptions] = useState<any>(
  //   info.inputList
  //     ? info.inputList
  //         .filter(input => input.variable)
  //         .map(input => {
  //           return { value: input.variable, label: input.variable }
  //         })
  //     : []
  // )

  // const editData = e => {
  //   const obj = {
  //     ...info,
  //     ...e
  //   }
  //   setInfo(obj)
  //   setFlowVariables(id, data.title, obj)
  //   setSourceOptions(
  //     obj.inputList
  //       ? obj.inputList
  //           .filter(input => input.variable)
  //           .map(input => {
  //             return { value: input.variable, label: input.variable }
  //           })
  //       : []
  //   )
  // }

  // 溯源信息处理后再加载页面内容
  const [loadContent, setLoadContent] = useState(false)
  useEffect(() => {
    setLoadContent(true)
  }, [sourceOptions])

  /* 模型 */
  const ModeItems: CollapseProps['items'] = [
    createCollapseItem(
      '1',
      <CollapseNodeComponent
        title="模型"
        tooltipText="向模型提供用户指令，如查询或任何基于文本输入的提问。"
      ></CollapseNodeComponent>,
      <LimModeCont info={info} editData={editData} />
    )
  ]
  /* 输入 */
  const OldInputItems: CollapseProps['items'] = [
    createCollapseItem(
      '6',
      <CollapseNodeComponent
        title="输入"
        tooltipText="输入需要添加到提示词的信息，这些信息可以被下方的提示词引用"
      ></CollapseNodeComponent>,
      <>{loadContent && <InputContNew info={info} sourceOptions={sourceOptions} editData={editData} />}</>
    )
  ]
  /* 用户提示词 */
  const InputItems: CollapseProps['items'] = [
    createCollapseItem(
      '2',
      <CollapseNodeComponent
        title="用户提示词"
        tooltipText="向模型提供用户指令，如查询或任何基于文本输入的提问。"
      ></CollapseNodeComponent>,
      <>{loadContent && <InputCont info={info} sourceOptions={sourceOptions} editData={editData} />}</>
    )
  ]
  // const CallWordItems: CollapseProps['items'] = [
  //   createCollapseItem('3', CallWordNode(), <CallWordCont cont={textValue} />)
  // ]
  /* 系统提示词 */
  const UserCallWordItems: CollapseProps['items'] = [
    createCollapseItem(
      '4',
      <CollapseNodeComponent
        title="系统提示词"
        tooltipText="为对话提供系统级指导，如设定人设和回复逻辑。"
      ></CollapseNodeComponent>,
      <>{loadContent && <UserCallWordCont info={info} sourceOptions={sourceOptions} editData={editData} />}</>
    )
  ]
  /* 输出 */
  const ExportationItems: CollapseProps['items'] = [
    createCollapseItem(
      '5',
      <CollapseNodeComponent title="输出" tooltipText="大模型运行完成后生成的内容"></CollapseNodeComponent>,
      <ExportationCont info={info} editData={editData} />
    )
  ]

  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      const obj = {
        ...info,
        ...flowVariables[data.id]
      }
      setInfo(obj)
      /* 单节点运行弹窗 */
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }
      setSourceOptions(getSourceOptions(obj))
    }
  }, [flowVariables])
  /* 单节点弹窗状体啊 */
  const [runDrawerHid, setrunDrawerHid] = useState(false)
  const showDrawer = () => {
    setrunDrawerHid(true)
  }

  const collapseItems = [
    { key: '1', title: '模型', items: ModeItems },
    { key: '6', title: '输入', items: OldInputItems },
    { key: '4', title: '系统提示词', items: UserCallWordItems },
    { key: '2', title: '用户提示词', items: InputItems },
    { key: '5', title: '输出', items: ExportationItems }
  ]
  const collapseProps = {
    bordered: false,
    expandIcon: ({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />,
    style: { background: token.colorBgContainer }
  }
  const renderCollapse = item => (
    <div className="lim_cardMarBot" key={item.key}>
      <Collapse {...collapseProps} defaultActiveKey={[item.key]} items={item.items} />
    </div>
  )

  return (
    <div className="workflow-common-panel flexCol lim_case caseOverFlowY">
      <span className="lim_title">调用大语言模型，根据输入参数和提示词生成回复</span>
      {/* 内容 */}
      {collapseItems.map(renderCollapse)}

      {/* 系统提示词 */}
      {/* <div className="lim_cardMarBot">
        <Collapse
          bordered={false}
          expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
          style={{ background: token.colorBgContainer }}
          items={CallWordItems}
        />
      </div> */}

      {/* 提示词优化弹窗 */}
      {callwordOpen ? (
        <OptionDia
          submitData={submitData}
          open={callwordOpen}
          setOpen={setCallWordOpen}
          obj={{ content: textValue }}
        ></OptionDia>
      ) : null}
      {/* 提示词列表 */}
      {callOpen && <CallWordDia addCallWord={addCallWord} open={callOpen} setOpen={setCallOpen}></CallWordDia>}
      {/* 抽屉 */}
      {runDrawerHid && <RunDrawer nodeData={info} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}
    </div>
  )
}

export default React.memo(LLMNode)
